package com.bcqn.controller;

import com.alibaba.fastjson.JSONObject;
import com.bcqn.common.CommonResponse;
import com.bcqn.model.Employee;
import com.bcqn.model.Role;
import com.bcqn.service.AdminService;
import com.bcqn.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("admin")
public class AdminController extends CommonController {


    @Resource
    private AdminService adminService;

    private void addCookie(HttpServletResponse response, Cookie cookie, boolean isHttpOnly) {
        String name = cookie.getName();
        String value = cookie.getValue();
        int maxAge = cookie.getMaxAge();
        String path = cookie.getPath();
        String domain = cookie.getDomain();
        boolean isSecure = cookie.getSecure();
        StringBuilder buffer = new StringBuilder();
        buffer.append(name).append("=").append(value).append(";");

        if (maxAge == 0) {
            buffer.append("Expires=Thu Jan 01 08:00:00 CST 1970;");
        } else if (maxAge > 0) {
            buffer.append("Max-Age=").append(maxAge).append(";");
        }
        if (domain != null) {
            buffer.append("domain=").append(domain).append(";");
        }
        if (path != null) {
            buffer.append("path=").append(path).append(";");
        }
        if (isSecure) {
            buffer.append("secure;");
        }
        if (isHttpOnly) {
            buffer.append("HTTPOnly;");
        }
        response.addHeader("Set-Cookie", buffer.toString());
    }

    private String getEmployeeId(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        try {
            for (Cookie cookie : cookies) {
                if ("_login_token".equals(cookie.getName())) {
                    String value = AESUtil.decode(cookie.getValue());
                    return value;
                }
            }
        } catch (Exception e) {
            log.error("cookie异常", e);
            return null;
        }
        return null;
    }

    private CommonResponse getCommonResponse(HttpServletResponse response, Employee user) {
        String eeId = user.getId().toString();
        Cookie logCookie = new Cookie("_login_token", AESUtil.encode(eeId));
        logCookie.setMaxAge(Integer.MAX_VALUE);
        logCookie.setPath("/");
        addCookie(response, logCookie, true);
        String jsonString = JSONObject.toJSONString(user);
        JSONObject userInfo = JSONObject.parseObject(jsonString);
        userInfo.remove("password");
        return CommonResponse.success(userInfo);
    }

    @PostMapping("/user/register")
    public CommonResponse register(@RequestParam(value = "userName", required = true) String userName,
                                   @RequestParam(value = "password", required = true) String password,
            HttpServletResponse response) {
        Employee user = adminService.getUserByUserName(userName);
        if(user == null) {
            user = new Employee();
            user.setPassword(password);
            user.setCreateTime(new Date());
            user.setUserName(userName);
            if (adminService.insertUser(user) == 1) {
                return getCommonResponse(response, user);
            } else {
                return CommonResponse.fail("注册异常");
            }
        } else {
            return CommonResponse.fail("该用户名已被占用");
        }
    }

    @PostMapping("/user/login")
    public CommonResponse login(@RequestParam(value = "password", required = true) String password,
                                @RequestParam(value = "userName", required = true) String userName, 
                                HttpServletResponse response) {
        Employee dbEmployee = adminService.getUserByUserName(userName);
        if (dbEmployee != null && dbEmployee.getPassword().equals(password)) {
            return getCommonResponse(response, dbEmployee);
        }
        return CommonResponse.fail("登录失败");
    }

    @GetMapping("/user/info/me")
    public CommonResponse info(HttpServletRequest request, HttpServletResponse response) {
        String id = getEmployeeId(request);
        Employee user = adminService.getUserInfoByEmployeeId(Long.parseLong(id));
        if (user != null) {
            return getCommonResponse(response, user);
        }
        return CommonResponse.fail("未登录");
    }

    @PostMapping("/user/info/update")
    public CommonResponse updateInfo(HttpServletRequest request, HttpServletResponse response) {
        String id = getEmployeeId(request);
        Employee user = adminService.getUserInfoByEmployeeId(Long.parseLong(id));
        if (user != null) {
            return getCommonResponse(response, user);
        }
        return CommonResponse.fail("未登录");
    }

     @PostMapping("/role/add")
     public CommonResponse updateRole(@RequestParam(value = "name", required = true) String name,
                                 @RequestParam(value = "resource", required = true) String resource,
                                 HttpServletResponse response) {
         Role role = new Role();
         role.setName(name);
         role.setResource(resource);
         if (adminService.insertRole(role) == 1) {
             return CommonResponse.success(role);
         }
         return CommonResponse.fail("登录失败");
     }

}